package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.FlightOrder;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IBlackListService;
import cn.wolfcode.luowowo.article.service.IFlightService;
import cn.wolfcode.luowowo.article.service.IPoiService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.article.vo.PoiDestVo;
import cn.wolfcode.luowowo.cache.service.IPoiRedisService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisVOService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisVOService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.comment.domain.PoiComment;
import cn.wolfcode.luowowo.comment.service.IPoiCommentService;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtils;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.List;

/**
 * 个人中心相关的控制器
 */
@Controller
@RequestMapping("mine")
public class MineController {

    @Reference
    private ITravelService travelService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private IStrategyCommentService strategyCommentService;
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    @Reference
    private ITravelStatisVOService travelStatisVOService;
    @Reference
    private IPoiCommentService poiCommentService;
    @Reference
    private IStrategyStatisVOService strategyStatisVOService;
    @Reference
    private IPoiRedisService poiRedisService;
    @Reference
    private IPoiService poiService;
    @Reference
    private IFlightService flightService;

    @Reference
    private IBlackListService blackListService;
    /**
     * 我的窝
     */
    @RequestMapping("/home")
    @RequireLogin
    public String home(Model model, @ModelAttribute("qo")TravelQuery qo, @UserParam UserInfo userInfo){
        qo.setUserId(userInfo.getId());
        model.addAttribute("pageInfo",travelService.query(qo));
        //attentions  查询当前用户的关注
        List<UserInfo> attentions = userInfoService.getAttentionsByCurrentUser(userInfo);
        int fansNum=0;
        Long[] fansIds = userInfo.getFansIds();
        if (fansIds!=null){
            fansNum= fansIds.length;
        }
//        model.addAttribute("userInfo",userInfo);
        model.addAttribute("attentions",attentions.isEmpty()? Collections.EMPTY_LIST:attentions);
        model.addAttribute("fansNum",fansNum==0?0:fansNum);
        //景点评论
        List<PoiComment> poiComments=poiCommentService.getByUserId(userInfo.getId());
        model.addAttribute("poiComments",poiComments);
        return "/mine/homepage";
    }

    /**
     * 我的游记
     */
    @RequestMapping("/myTravelNotes")
    @RequireLogin
    public String myTravelNotes(Model model, @ModelAttribute("qo")TravelQuery qo, @UserParam UserInfo userInfo){
        qo.setUserId(userInfo.getId());
        model.addAttribute("useInfo",userInfo);
        //查询所有游记
        PageInfo pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo",pageInfo);
        //处理我的总阅读数,游记总数
        long replynum = 0;
        long viewnum = 0;
        List list = pageInfo.getList();
        for (int i = 0; i < list.size(); i++) {
            Travel travel = (Travel) list.get(i);
            replynum += travel.getReplynum();
            viewnum+=travel.getViewnum();
        }
        model.addAttribute("replynum",replynum);
        model.addAttribute("viewnum",viewnum);
        return "/mine/mytravelnotes";
    }

    /**
     * 我的点评
     */
    @RequestMapping("/review")
    @RequireLogin
    public String review(Model model,@UserParam UserInfo userInfo){
        List<PoiComment> poiComments=poiCommentService.getByUserId(userInfo.getId());
        model.addAttribute("poiComments",poiComments);
        return "/mine/review";
        //更新了
    }

    /**
     * 我的收藏
     */
    @RequestMapping("/travelcollection")
    @RequireLogin
    public String travelCollection(Model model, @UserParam UserInfo userInfo){
//        List<TravelStatisVO> list=travelStatisVOService.getTravelStatisVOByUserId(userInfo.getId());
        if(userInfo==null){
            throw new LogicException("请先登录");
        }
        List<Long> tids = travelStatisVOService.getFavorTravelsByUser(userInfo.getId());
        List<Travel> travels = travelService.queryTravels(tids);
        model.addAttribute("travels", travels);

        List<Long> sids = strategyStatisVOService.getFavorStrategiesByUser(userInfo.getId());
        List<StrategyDetail> strategies = strategyDetailService.queryStrategies(sids);
        model.addAttribute("strategies", strategies);

        List<Long> pids = poiRedisService.getFavorPoisByUser(userInfo.getId());
        List<PoiDestVo> poisAndDest = poiService.queryPoisAndDest(pids);
        model.addAttribute("poisAndDest", poisAndDest);

        return "/mine/travelcollection";
    }
    /**
     * 我的设置
     */
    @RequestMapping("/setting")
    @RequireLogin
    public String setting(Model model,@UserParam UserInfo userInfo){
        String userPhone = userInfo.getPhone().substring(0, 3) + "****" + userInfo.getPhone().substring(7);
        UserInfo user = userInfoService.get(userInfo.getId());
        model.addAttribute("userInfo",user);
        model.addAttribute("userPhone",userPhone);
        //查询我的黑名单
        List<UserInfo> ublackList=userInfoService.queryByUserId(userInfo.getId());
        model.addAttribute("blackList",ublackList);
        return "/mine/setting";
    }
    @RequestMapping("/updateUserInfo")
    @RequireLogin
    public String updateUserInfo(UserInfo user,@UserParam UserInfo userInfo){
        user.setId(userInfo.getId());
        userInfoService.updateUserInfo(user);
        return "redirect:/mine/setting";
    }

    /**
     * 修改用户头像
     * @param files
     * @param userInfo
     * @return
     */
    @Value("${file.path}")
    private String basePath;
    @RequestMapping("/uploadImg")
    @RequireLogin
    public String uploadImg(MultipartFile files, @UserParam UserInfo userInfo) {
        String upload = UploadUtil.upload(files, basePath);
        userInfo.setHeadImgUrl("/"+upload);
        userInfoService.updateUserInfo(userInfo);
        return "redirect:/mine/setting";
    }

    /**
     * 账号和安全
     */
    @RequestMapping("/sendOldPhoneVerifyCode")
    @RequireLogin
    @ResponseBody
    public Object sendOldPhoneVerifyCode(String phone){
       userInfoService.sendVerifyCode(phone);
        return AjaxResult.success();
    }

    /**
     * 新的手机号
     * @param newMobile
     * @return
     */
    @RequestMapping("/sendNewPhoneVerifyCode")
    @ResponseBody
    public Object sendNewPhoneVerifyCode(String newMobile){
       userInfoService.sendVerifyCode(newMobile);
       return AjaxResult.success();
    }
    /**
     * 检查旧的验证码是否正确
     */
    @RequestMapping("/checkVerifyCode")
    @ResponseBody
    public Object checkVerifyCode(String phone,String code){
        String key = RedisKeys.VERIFY_CODE.join(phone);
        String verifyCode = userInfoRedisService.getNewVerifyCode(key);
        System.out.println("++++++++++++");
        System.out.println(verifyCode);
        if(code==null||!code.equalsIgnoreCase(verifyCode)){
            throw new LogicException("验证码不正确或已过期~");
        }
        return AjaxResult.success();
    }
    /**
     * 验证新的验证码
     */
    @RequestMapping("/setNewPhone")
    @ResponseBody
    public Object setNewPhone(String newMobile,String verifyCode,@UserParam UserInfo userInfo){
        String key = RedisKeys.VERIFY_CODE.join(newMobile);
        String code = userInfoRedisService.getNewVerifyCode(key);
        if(code==null||!code.equalsIgnoreCase(verifyCode)){
            throw new LogicException("验证码不正确或已过期");
        }
        if(newMobile.equals(userInfo.getPhone())){
            throw new LogicException("请不要与之前手机号一样");
        }
        userInfoService.updatePhone(userInfo.getPhone(),newMobile);
        return AjaxResult.success();
    }
    /**
     * 注销信息
     */
    @RequestMapping("/delete")
    @RequireLogin
    @ResponseBody
    public Object delete(HttpServletRequest request, HttpServletResponse response, @UserParam UserInfo userInfo){
        userInfoService.deleteUser(userInfo.getId())    ;
        HttpSession session = request.getSession();
        if (session != null) {
            session.invalidate();//触发LogoutListener
        }
        Cookie[] cookies = request.getCookies();
        String token=null;
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals(CookieUtils.getToken(request))){
                //Cookie ck = new Cookie(RedisKeys.LOGIN_TOKEN.toString(),token);
                cookie.setMaxAge(0);
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }
        }
        return AjaxResult.success();
    }

    @RequestMapping("/orders")
    public String orders(Model model, @UserParam UserInfo userInfo){
        if(userInfo==null){
            throw new LogicException("请先登录");
        }
        List<FlightOrder> flights = flightService.queryByUser(userInfo.getId());
        model.addAttribute("flights", flights);
        return "mine/orders";
    }
    @RequestMapping("/address")
    @RequireLogin
    public String addAddress() {
        return "/mine/address";
    }

}
